package com.rran.study.designpattern.behavioral.observer.publisher;

import com.rran.study.designpattern.behavioral.observer.event.app.AppEvent;
import com.rran.study.designpattern.behavioral.observer.factory.AppEventListenerFactory;
import com.rran.study.designpattern.behavioral.observer.listener.app.AppListener;
import org.springframework.util.Assert;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yy
 * @Type AppOrderEventPublisher.java
 * @Desc
 * @date 2020/7/21 20:06
 */
public class AppEventContext implements AppEventPublisher {

    private ExecutorService taskExecutor;

    public Executor getTaskExecutor() {
        return taskExecutor;
    }

    public void setTaskExecutor(ExecutorService taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public AppEventContext() {
        //定义一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        this.setTaskExecutor(executorService);
    }

    @Override
    public void publish(AppEvent event, boolean async) {
        Executor executor = this.getTaskExecutor();
        String eventName = event.getEventName();
        Assert.notNull(eventName, "Event type must not be null");
        List<AppListener> listeners = AppEventListenerFactory.getListenerList(eventName);
        for (AppListener listener : listeners) {
            if (executor != null && async) {
                executor.execute(() -> {
                    this.invokeListener(listener, event);
                });
            } else {
                this.invokeListener(listener, event);
            }
        }
    }

    protected void invokeListener(AppListener listener, AppEvent event) {
        listener.applicationEvent(event);
    }

    public void close(){
        taskExecutor.shutdown();
    }

}
